import json

from re_common.baselibrary.tools.all_requests.aiohttp_request import AioHttpRequest
from re_common.baselibrary.tools.all_requests.mrequest import MRequest
from re_common.baselibrary.utils.core.mdeprecated import try_except2_async, try_except2, retry_func_async
# from apps.crawler_platform.core_callback.err_callback import all_client_back_callback
from re_common.baselibrary.utils.core.requests_core import INSIDE_HEADERS

from settings import get_settings


async def get_obj_proxy():
    """
    获取代理接口
    """
    url = get_settings().TAIYANG_REDIS_PROXY_URL_OBJ_QINGTING
    rrq = RequestApiHelper.get_rrq()
    kwargs = {
        "rrq": rrq,
        "header": INSIDE_HEADERS,
        "url": url,
        "timeout": 30,
        "data": "",
        "moths": MRequest.GET,
        "middler_list": [rrq.status_code_middlerwares, rrq.is_none_html_middlerwares, rrq.is_null_html_middlerwares,
                         rrq.msg_status_code_middlerwares]
    }
    bools, dicts = await RequestApiHelper.etl_remote_meta(**kwargs)
    if bools:
        proxy = json.loads(rrq.html)["data"]
        return bools, proxy
    else:
        return bools, 'nothing'


class RequestApiHelper(object):
    """
    在api发送http请求的工具类
    """

    def __init__(self):
        pass

    @classmethod
    def get_rrq(cls):
        return AioHttpRequest()

    @classmethod
    async def __base_aiorequest(cls, **kwargs):
        """
        类内部调用该方法
        :param kwargs:
        :return:
        """
        headers = kwargs.get("header", None)
        url = kwargs.get("url", None)
        data = kwargs.get("data", None)
        middler_list = kwargs.get("middler_list", None)
        moths = kwargs.get("moths", None)
        marks = kwargs.get("marks", [])
        proxy = kwargs.get("proxy", None)
        resp_encoding = kwargs.get("resp_encoding", None)
        sn = kwargs.get("sn", None)
        cookies = kwargs.get("cookies", None)
        resp_errors = kwargs.get("resp_errors", "strict")
        rrq = kwargs.get("rrq", None)
        timeout = kwargs.get("timeout", None)
        allow_redirects = kwargs.get("allow_redirects", True)
        allow_resp_text = kwargs.get("allow_resp_text", True)
        allow_resp_bytes = kwargs.get("allow_resp_bytes", False)

        rrq.set_url(url) \
            .set_header(headers) \
            .set_data(data) \
            .set_timeout(timeout) \
            .set_middler_list(middler_list) \
            .set_allow_redirects(allow_redirects) \
            .set_resp_encoding(resp_encoding) \
            .set_cookies(cookies) \
            .set_marks(marks) \
            .set_resp_errors(resp_errors) \
            .set_sn(sn) \
            .set_proxy(proxy) \
            .set_allow_resp_text(allow_resp_text) \
            .set_allow_resp_bytes(allow_resp_bytes)
        rrq.kwargs["verify_ssl"] = False
        bools, status_msg_dict = await rrq.run(moths)
        return bools, status_msg_dict, rrq

    @classmethod
    async def pare_rule(cls, **kwargs):
        bools, status_msg_dict, rrq = await cls.__base_aiorequest(**kwargs)
        return bools, status_msg_dict

    @classmethod
    async def proxy_api(cls, **kwargs):
        bools, status_msg_dict, rrq = await cls.__base_aiorequest(**kwargs)
        return bools, status_msg_dict

    @classmethod
    async def etl_remote_meta(cls, **kwargs):
        bools, status_msg_dict, rrq = await cls.__base_aiorequest(**kwargs)
        return bools, status_msg_dict


    @classmethod
    @retry_func_async(retry_times=3, sleep_time=1)
    async def down_obj(cls, proxy_type, google_proxy,  **kwargs):
        if proxy_type == "1":
            proxies = google_proxy
        else:
            bools, proxies = await get_obj_proxy()
        kwargs["proxy"] = proxies
        bools, status_msg_dict, rrq = await cls.__base_aiorequest(**kwargs)
        return bools, status_msg_dict

    @classmethod
    async def chaoxing_cookie(cls, **kwargs):
        bools, status_msg_dict, rrq = await cls.__base_aiorequest(**kwargs)
        return bools, status_msg_dict

    @classmethod
    async def mongo_save(cls, **kwargs):
        bools, status_msg_dict, rrq = await cls.__base_aiorequest(**kwargs)
        return bools, status_msg_dict

    @classmethod
    async def normal_request(cls, **kwargs):
        bools, status_msg_dict, rrq = await cls.__base_aiorequest(**kwargs)
        return bools, status_msg_dict
